﻿using AutoMapper;
using SqlSugar;
using SX.Core;
using SX.Core.EventBus.Abstractions;
using SX.Core.EventBus.Db;
using SX.ProductService.Repository.Core;
using SX.ProductService.Repository.Entity;
using SX.ProductService.Service.Events;
using SX.ProductService.Service.Implement.Product.ViewModel;
using SX.ProductService.Service.Interface;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace SX.ProductService.Service.Implement.Product
{
    public class ProductService :DbContext, IProductService
    {
        private readonly IMapper _mapper;
        private IEventBus _eventBus;
        private readonly IEventLogService _eventLogService;

        public ProductService(IMapper mapper,IEventBus eventBus,IEventLogService eventLogService)
        {
            _eventBus = eventBus;
            _eventLogService = eventLogService;
            _mapper = mapper;
        }
        public async Task<IApiResult> Add(ProductAddModel model)
        {
            var product = _mapper.Map<ProductEntity>(model);
            product.Id = GuidHelper.NewSequentialGuid();
            var res = await Db.Insertable<ProductEntity>(product).ExecuteCommandAsync();
            //发送mq事件消息
            if (res > 0)
            {
                ProductAddIntegrationEvent @event = new ProductAddIntegrationEvent
                {
                    BusinessId = product.Id,
                    Id = GuidHelper.NewSequentialGuid()
                };
                //添加消息记录到数据库
                await _eventLogService.AddEventTodbAsync(@event);
                //发送消息
                _eventBus.Publish(@event);
            }
            return ApiResult.Result(res > 0);
        }

        public async Task<IApiResult> Query(ProductQueryModel model)
        {
            RefAsync<int> total = 0;
            var queryable = Db.Queryable<ProductEntity>();
            var source = await queryable
                .OrderBy(x => x.CreateTime, OrderByType.Desc)
                .WhereIF(model.ProductName.NotNull(), x => x.ProductName.Contains(model.ProductName))
                .ToPageListAsync(model.PageIndex, model.PageSize, total);
            PageResult<ProductEntity> result = new PageResult<ProductEntity>()
            {
                Rows = source,
                TotalCount = total
            };
            return ApiResult.Ok(result);
        }
    }
}
